﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TarreOA.TarreOADAL;
using System.Data.SqlClient;

public partial class DutyReport_admin_CreateManage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] nights = Request.Form.GetValues("night");
        string[] daytimes = Request.Form.GetValues("daytime");
        string[] fugles = Request.Form.GetValues("fugle");
        int curMonth = int.Parse(Request.Form.Get("hidMonth"));
        int curYear = int.Parse(Request.Form.Get("hidYear"));
        int days = DateTime.DaysInMonth(curYear, curMonth);
        if(nights != null && daytimes != null && fugles != null)
        {
            if(nights.Length == daytimes.Length && daytimes.Length == fugles.Length && fugles.Length == days)
            {
                if(create(nights, daytimes, fugles, curMonth, curYear))
                {
                    Response.Redirect("ManageIndex.aspx?action=success");
                }
            }
        }
    }

    private bool create(string[] nights, string[] daytimes, string[] fugles, int curMonth, int curYear)
    {
        SqlConnection sqlConn = null;
        SqlCommand sqlCmd = null;
        try
        {
            sqlConn = SQLManager.GetConn();
            sqlConn.Open();
            int year = DateTime.Now.Year;
            string sql = "delete from dutyreport where [month]=" + curMonth + " and [year]=" + curYear;
            for(int i = 0; i < nights.Length; i++)
            {
                sql += " insert into dutyreport values(" + (i + 1) + "," + curMonth + "," + year +  ",'" + nights[i] + "','" + daytimes[i] + "','" + fugles[i] + "') ";
            }
            sqlCmd = new SqlCommand(sql, sqlConn);
            sqlCmd.ExecuteNonQuery();
            return true;
        }
        catch(Exception ex)
        {
            Response.Write(ex.Message);
            Console.WriteLine(ex.Message);
        }
        finally
        {
            if(sqlConn != null && sqlConn.State == ConnectionState.Open)
            {
                sqlConn.Close();
                sqlConn.Dispose();
            }
        }
        return false;
    }
}
